package bot

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net/http"
	"os"
	"strconv"

	"github.com/sirupsen/logrus"
)

type WelderHandler struct {
}

func NewWelderHandler() *WelderHandler {
	return &WelderHandler{}
}

func (weld *WelderHandler) Sleep() int {

	r := rand.Intn(3) + 2
	// time.Sleep(time.Duration(r))
	return r
}

func (weld *WelderHandler) GetCurrentlyCraftParameter(w http.ResponseWriter, r *http.Request) {
	fmt.Println("GetCurrentlyCraftParameter ")
	if r.Method == "GET" {
		w.Header().Set("Content-Type", "application/json")

		inputFile := "webserver/assets/bot/welder/welder_getCurentlyCraftParameters.json"

		inputReader, error := os.Open(inputFile)

		if error != nil {
			println("Error ", error)
			io.WriteString(w, "response is error ")
		} else {
			// buf, err := os.ReadFile(inputFile)

			// inputReader = bufio.NewReader(inputReader)

			// io.WriteString()
			io.Copy(w, inputReader)
			inputReader.Close()
		}
	} else {
		data := make(map[string]interface{})
		data["code"] = 200
		data["body"] = make(map[string]interface{})
		data["msg"] = "the api must be post method "

		jsonByte, _ := json.Marshal(data)
		str := string(jsonByte)
		io.WriteString(w, str)
	}
}

/*
选择焊接参数
*/
/* 选择工艺参数 */
func (weld *WelderHandler) CraftParametersSelection(w http.ResponseWriter, r *http.Request) {
	fmt.Println("CraftParametersSelection ")
	if r.Method == "GET" {
		w.Header().Set("Content-Type", "application/json")

		r.ParseForm()
		id := r.Form.Get("id")
		if id == "" {
			body := make(map[string]interface{})
			data := make(map[string]interface{})
			data["code"] = 500
			body["msg"] = "id cannot be empty"
			data["body"] = body
			data["msg"] = "id cannot be empty"

			jsonByte, _ := json.Marshal(data)
			str := string(jsonByte)
			io.WriteString(w, str)
		} else {
			data := make(map[string]interface{})
			data["code"] = 200
			data["body"] = make(map[string]interface{})
			data["msg"] = "welder/craftParametersSelection"

			jsonByte, _ := json.Marshal(data)
			str := string(jsonByte)
			io.WriteString(w, str)
		}

	}
}

/*
焊丝微动
*/
func (weld *WelderHandler) CommonControl(w http.ResponseWriter, r *http.Request) {
	fmt.Println("CommonControl ")
	t := weld.Sleep()
	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/json")
		r.ParseForm()
		var response = make(map[string]interface{})
		weldingWireMove, isGasDetection, isPointFeedWire := "", "", ""
		if r.Form.Has("weldingWireMove") {
			weldingWireMove = r.Form.Get("weldingWireMove")
		}
		if r.Form.Has("isGasDetection") {
			isGasDetection = r.Form.Get("isGasDetection")
		}
		if r.Form.Has("isPointFeedWire") {
			isPointFeedWire = r.Form.Get("isPointFeedWire")
		}

		response["code"] = 200
		response["msg"] = "success"
		response["data"] = map[string]string{
			"result":          "1",
			"weldingWireMove": weldingWireMove,
			"isGasDetection":  isGasDetection,
			"isPointFeedWire": isPointFeedWire,
			"msg":             "WeldWire normal",
			"rand":            strconv.Itoa(t)}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	}
}

/*
查询报警
*/
func (weld *WelderHandler) QueryAlarm(w http.ResponseWriter, r *http.Request) {
	fmt.Println("QueryAlarm ")
	t := weld.Sleep()
	switch r.Method {
	case "GET":
		w.Header().Set("Content-Type", "application/json")
		r.ParseForm()
		var response = make(map[string]interface{})
		if r.Form.Has("level") {
			sLevel := r.Form.Get("level")
			level, _ := strconv.Atoi(sLevel)
			response["code"] = 200
			response["msg"] = "success"
			data := map[string]string{"msg": "QueryAlarm success", "rand": strconv.Itoa(t)}
			data["alarm_level"] = strconv.Itoa(level)
			response["data"] = data
		} else {

			response["code"] = 200
			response["msg"] = "success"
			response["data"] = map[string]string{"msg": "QueryAlarm success", "rand": strconv.Itoa(t)}
		}

		jsonByte, _ := json.Marshal(response)
		str := string(jsonByte)
		log.Println("res: ", str)
		fmt.Println("res: ", str)
		io.WriteString(w, str)
	}
}

func (weld *WelderHandler) GetCraftSelector(w http.ResponseWriter, r *http.Request) {
	fmt.Println("GetCraftSelector ")
	if r.Method == "GET" || r.Method == "POST" {

		inputFile := "webserver/assets/bot/welder/welder_getCraftSelector.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			println("Error ", error)
		} else {
			// buf, err := os.ReadFile(inputFile)

			// inputReader = bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			// io.WriteString()
			io.Copy(w, inputReader)
		}
	}
}

func (weld *WelderHandler) GetCraftParametersList(w http.ResponseWriter, r *http.Request) {
	logrus.Print("GetCraftParametersList ")
	if r.Method == "GET" || r.Method == "POST" {

		inputFile := "webserver/assets/bot/welder/welder_getCraftParametersList.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			println("Error ", error)
		} else {
			// buf, err := os.ReadFile(inputFile)
			inputReader := bufio.NewReader(inputReader)
			// for {
			// 	inputBytes, err := inputReader.ReadBytes('\n') // 循环读取文件内容，每次以 '\n'字符为一次读取的终止
			// 	inputString := string(inputBytes)
			// 	fmt.Printf("== inputString: %v\n", inputString)
			// 	if err == io.EOF { // 文件结束
			// 		return
			// 	}
			// }
			// inputReader = bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			// io.WriteString()
			io.Copy(w, inputReader)
		}
	}
}

func (weld *WelderHandler) GetCraftParametersListBySelect(w http.ResponseWriter, r *http.Request) {
	fmt.Println("GetCraftParametersListBySelect ")
	if r.Method == "POST" {

		w.Header().Set("Content-Type", "application/json")
		body := make(map[string]interface{})
		err := json.NewDecoder(r.Body).Decode(&body)
		if err != nil {
			io.WriteString(w, "request body has some errors "+err.Error())
			return
		}
		defer r.Body.Close()

		materials := body["materials"].(float64)
		plateThickness := body["plateThickness"]
		weldingWire := body["weldingWire"]
		fmt.Println("GetParametersListBySelect== ", "materials ", materials, "plateThickness ", plateThickness, "weldingWire ", weldingWire)

		inputFile := ""
		if materials == 0 {
			inputFile = "webserver/assets/bot/welder/welder_getParametersListBySelect0.json"
		} else if materials == 1 {
			inputFile = "webserver/assets/bot/welder/welder_getParametersListBySelect1.json"
		} else if materials == 2 {
			inputFile = "webserver/assets/bot/welder/welder_getParametersListBySelect2.json"
		}

		inputReader, error := os.Open(inputFile)

		if error != nil {
			println("Error ", error)
			io.WriteString(w, "response is error ")
		} else {
			// buf, err := os.ReadFile(inputFile)

			// inputReader = bufio.NewReader(inputReader)

			// io.WriteString()
			io.Copy(w, inputReader)
			inputReader.Close()
		}
	} else {
		data := make(map[string]interface{})
		data["code"] = 200
		data["body"] = make(map[string]interface{})
		data["msg"] = "the api must be post method "

		jsonByte, _ := json.Marshal(data)
		str := string(jsonByte)
		io.WriteString(w, str)
	}
}

func (weld *WelderHandler) SaveCraftParameters(w http.ResponseWriter, r *http.Request) {
	fmt.Println("SaveCraftParameters ")
	if r.Method == "GET" || r.Method == "POST" {

		inputFile := "webserver/assets/bot/welder/welder_saveCraftParameters.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			println("Error ", error)
		} else {
			// buf, err := os.ReadFile(inputFile)
			inputReader := bufio.NewReader(inputReader)
			// for {
			// 	inputBytes, err := inputReader.ReadBytes('\n') // 循环读取文件内容，每次以 '\n'字符为一次读取的终止
			// 	inputString := string(inputBytes)
			// 	fmt.Printf("== inputString: %v\n", inputString)
			// 	if err == io.EOF { // 文件结束
			// 		return
			// 	}
			// }
			// inputReader = bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			// io.WriteString()
			io.Copy(w, inputReader)
		}
	}
}

func (weld *WelderHandler) WeavingWeldSwitch(w http.ResponseWriter, r *http.Request) {
	fmt.Println("WeavingWeldSwitch ssss ", r.Method)
	if r.Method == "GET" {
		w.Header().Set("Content-Type", "application/json")
		r.ParseForm()
		value := r.Form.Get("value")

		inputFile := ""
		if value == "1" {
			inputFile = "webserver/assets/bot/welder/welder_weavingWeldSwitch1.json"
		} else {
			inputFile = "webserver/assets/bot/welder/welder_weavingWeldSwitch0.json"
		}

		inputReader, error := os.Open(inputFile)

		if error != nil {
			println("Error ", error)
			io.WriteString(w, "response is error ")
		} else {
			io.Copy(w, inputReader)
			inputReader.Close()
		}
	}
}

func (weld *WelderHandler) QueryWeavingWeldParameter(w http.ResponseWriter, r *http.Request) {
	fmt.Println("QueryWeavingWeldParameter ")
	if r.Method == "GET" {
		w.Header().Set("Content-Type", "application/json")
		r.ParseForm()
		gValue := r.Form.Get("value")
		inputFile := ""
		if gValue == "1" {
			inputFile = "webserver/assets/bot/welder/welder_queryWeavingWeldParameter1.json"
		} else {
			inputFile = "webserver/assets/bot/welder/welder_queryWeavingWeldParameter0.json"
		}

		inputReader, error := os.Open(inputFile)

		if error != nil {
			println("Error ", error)
			io.WriteString(w, "response is error ")
		} else {
			io.Copy(w, inputReader)
			inputReader.Close()
		}
	}
}

/* 获取机器人的连接状态 */
func (cobot *WelderHandler) SetArcingParameters(w http.ResponseWriter, r *http.Request) {
	print("SetArcingParameters ")
	logrus.Debug("Entry")
	if r.Method == "GET" || r.Method == "POST" {
		// w.WriteHeader(http.StatusNotFound)
		// w.Write([]byte("oops"))
		// return
		// 读取文件内容
		inputFile := "webserver/assets/bot/welder/welder_setArcingParameters.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			// io.WriteString()
			io.Copy(w, inputReader)
		}
	}
}

func (cobot *WelderHandler) SetQuenchingResidenceTime(w http.ResponseWriter, r *http.Request) {
	print("SetQuenchingResidenceTime ")
	logrus.Debug("Entry")
	if r.Method == "GET" {

		r.ParseForm()
		time := r.Form.Get("time")
		print("SetQuenchingResidenceTime time is ", time)
		// 读取文件内容
		inputFile := "webserver/assets/bot/welder/welder_setQuenchingResidenceTime.json"

		inputReader, error := os.Open(inputFile)
		if error != nil {
			logrus.Error(error)
		} else {
			inputReader := bufio.NewReader(inputReader)
			w.Header().Set("Content-Type", "application/json")
			r.ParseForm()
			// io.WriteString()
			io.Copy(w, inputReader)
		}
	}
}

func (weld *WelderHandler) UpdateWeavingWeldParameter(w http.ResponseWriter, r *http.Request) {
	fmt.Println("UpdateWeavingWeldParameter ")
	if r.Method == "POST" {
		w.Header().Set("Content-Type", "application/json")
		body, err := io.ReadAll(r.Body)
		if err != nil {
			io.WriteString(w, "request body has some errors "+err.Error())
			return
		}
		defer r.Body.Close()
		var data map[string]interface{}
		err = json.Unmarshal(body, &data)
		if err != nil {
			io.WriteString(w, "unmarshall some errors "+err.Error())
			return
		}
		modeType := data["modeType"].(float64)
		frequency := data["frequency"].(float64)
		width := data["width"].(float64)
		horizontalAngle := data["horizontalAngle"].(float64)
		verticalAngle := data["verticalAngle"].(float64)
		stay_left := data["stay_left"].(float64)
		stay_right := data["stay_right"].(float64)

		fmt.Println("UpdateWeavingWeldParameter== ", "modeType ", modeType, "horizontalAngle", horizontalAngle, "verticalAngle", verticalAngle, "frequency ", frequency, "width ", width, "stay_left ", stay_left, "stay_right ", stay_right)

		inputFile := ""
		if modeType == 1 {
			inputFile = "webserver/assets/bot/welder/welder_updateWeavingWeldParameter1.json"
		} else {
			inputFile = "webserver/assets/bot/welder/welder_updateWeavingWeldParameter0.json"
		}

		inputReader, error := os.Open(inputFile)

		if error != nil {
			println("Error ", error)
			io.WriteString(w, "response is error ")
		} else {
			// buf, err := os.ReadFile(inputFile)

			// inputReader = bufio.NewReader(inputReader)

			// io.WriteString()
			io.Copy(w, inputReader)
			inputReader.Close()
		}
	}
}
